package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {


        //获取之前点击验证码按钮获取的验证码，与页面传来的验证码数据做比较
        String oldcode = (String) session.getAttribute("code");


        String phone = map.get("phone");
        String code = map.get("code");

        if (!oldcode.equals(code)) {

            return R.error("验证码错误，请重新输入！");
        }

        User user = userService.findUserByPhone(phone);

        if (user == null) {


            //组装用户信息
            user = new User();

            user.setStatus(1);
            user.setPhone(phone);
            user.setName("瑞吉用户" + user.getPhone());

            //如果用户不存在，说明用户第一次访问，需要将用户的信息添加到数据库里
            userService.add(user);


        }
        session.setAttribute("user", user);

        return R.success("登录成功！");

    }


    @PostMapping("/logout")
    public R logout(HttpSession session)
    {
        try {
            //把登录成功的时候，保存的员工数据给删除掉
            //session.removeAttribute("employee");

            //直接把session给干掉
            session.invalidate();

            return R.success("退出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退出失败！");
        }
    }
}
